﻿using Assimp;
using Assimp.Configs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenTKBasics.AssimpNet
{
    public class AssimpOperator
    {
        public List<Assimp.Mesh> meshes = new List<Assimp.Mesh>();
        string directory = string.Empty;

        public void LoadFile(string path)
        {
            directory = Path.GetDirectoryName(path);
            Console.WriteLine(directory);

            //Filepath to our model String fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Seymour.dae");

            //Create a new importer
            AssimpContext importer = new AssimpContext();

            //This is how we add a configuration (each config is its own class)
            NormalSmoothingAngleConfig config = new NormalSmoothingAngleConfig(66.0f);
            importer.SetConfig(config);

            //This is how we add a logging callback 
            LogStream logstream = new LogStream(delegate (String msg, String userData)
            {
                Console.WriteLine(msg);
            });
            logstream.Attach();

            //Import the model. All configs are set. The model
            //is imported, loaded into managed memory. Then the unmanaged memory is released, and everything is reset.
            Scene scene = importer.ImportFile(
                path,
                PostProcessPreset.TargetRealTimeMaximumQuality
                | PostProcessSteps.PreTransformVertices
                | PostProcessSteps.Triangulate
                | PostProcessSteps.FlipUVs
                | PostProcessSteps.CalculateTangentSpace
                );
             
            if (scene == null || scene.SceneFlags == SceneFlags.Incomplete || scene.RootNode == null)
            { Console.WriteLine("ERROR::ASSIMP"); return; }

            Console.WriteLine("================Model_Loaded");
            //TODO: Load the model data into your own structures

            ProcessNode(scene.RootNode ,ref scene);

            Console.WriteLine("================ProcessNode_Done");

            //End of example
            importer.Dispose();
        }
          
        void ProcessNode(Node node ,ref Scene scene)
        {
            Console.WriteLine(node.Name);

            foreach (int num in node.MeshIndices)
            {
                meshes.Add(scene.Meshes[num]);
            }
            
            foreach (Node item in node.Children)
            {
                ProcessNode(item, ref scene);
            }
        }

    }
}
